/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意：
* 本软件为www.yixiang.co开发研制，未经购买不得使用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package co.yixiang.modules.product.rest;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.constant.ShopConstants;
import co.yixiang.domain.PageResult;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.logging.aop.log.Log;
import co.yixiang.modules.product.domain.YxPrize;
import co.yixiang.modules.product.service.YxPrizeService;
import co.yixiang.modules.product.service.YxPrizeService;
import co.yixiang.modules.product.service.dto.YxPrizeDto;
import co.yixiang.modules.product.service.dto.YxPrizeQueryCriteria;
import co.yixiang.modules.product.service.dto.YxPrizeQueryCriteria;
import co.yixiang.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
* @author lsh
* @date 2021-07-20
*/
@AllArgsConstructor
@Api(tags = "YxPrize管理")
@RestController
@RequestMapping("/api")
public class YxPrizeController {

    private final YxPrizeService yxPrizeService;
    private final IGenerator generator;
    private final RedisUtils redisUtils;
    private final RedisTemplate<String, String> redisTemplate;


    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/yxPrize/download")
    @PreAuthorize("@el.check('admin','yxPrize:list')")
    public void download(HttpServletResponse response, YxPrizeQueryCriteria criteria) throws IOException {
        yxPrizeService.download(generator.convert(yxPrizeService.queryAll(criteria), YxPrizeDto.class), response);
    }

    @GetMapping(value = "/yxPrize")
    @Log("查询YxPrize")
    @ApiOperation("查询YxPrize")
    @PreAuthorize("hasAnyRole('admin','YXPRIZE_ALL','YXPRIZE_SELECT')")
    public ResponseEntity<PageResult<YxPrizeDto>> getYxPrizes(YxPrizeQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(yxPrizeService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping(value = "/yxPrize")
    @Log("新增YxPrize")
    @ApiOperation("新增YxPrize")
    @PreAuthorize("hasAnyRole('admin','YXPRIZE_ALL','YXPRIZE_CREATE')")
    public ResponseEntity<Object> create(@Validated @RequestBody YxPrize resources){
        yxPrizeService.save(resources);
        if(ObjectUtil.isNotNull(resources.getEndDate())) {
            long time =resources.getEndDate().getTime()-new Date().getTime();
            if(time>0){
                String redisKey = String.valueOf(StrUtil.format("{}{}",
                        ShopConstants.PRIZE_END_TIME,resources.getId().toString()));
                redisTemplate.opsForValue().set(redisKey, resources.getId().toString(), time/1000, TimeUnit.SECONDS);
            }
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping(value = "/yxPrize")
    @Log("修改YxPrize")
    @ApiOperation("修改YxPrize")
    @PreAuthorize("hasAnyRole('admin','YXPRIZE_ALL','YXPRIZE_EDIT')")
    public ResponseEntity<Object> update(@Validated @RequestBody YxPrize resources){
        YxPrize prize =yxPrizeService.getById(resources.getId());
        if(resources.getEndDate().getTime() !=prize.getEndDate().getTime()){
            long time =resources.getEndDate().getTime()-new Date().getTime();
            if(time>0){
                String redisKey = String.valueOf(StrUtil.format("{}{}",
                        ShopConstants.PRIZE_END_TIME,prize.getId().toString()));
                redisTemplate.opsForValue().set(redisKey, prize.getId().toString(), time/1000, TimeUnit.SECONDS);
            }
        }
        yxPrizeService.updateById(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除YxPrize")
    @ApiOperation("删除YxPrize")
    @PreAuthorize("hasAnyRole('admin','YXPRIZE_ALL','YXPRIZE_DELETE')")
    @DeleteMapping(value = "/yxPrize/{id}")
    public ResponseEntity<Object> deleteAll(@PathVariable Long id) {
            yxPrizeService.removeById(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
